#!/usr/bin/env python
# -*- encoding=utf8-*-
from stockin import Stockin
from mylog import MyLog
import settings,preprocess
import re,os,sys,time,shutil

log = MyLog()
a = Stockin()
z = a.get_files(settings.SRCDATA_DIR,settings.FILE_SUFFIX)
for src_file in z:
    if src_file:
        pure_file_name = preprocess.get_file_namestr(src_file)
        if preprocess.get_legal_load_file(src_file):
            load_file = preprocess.read_process_write(src_file)
            try:
                log_str = a.stockin_exec(load_file)
                log.info(log_str.strip())
            except Exception,e:
                log.error('*******load faild!*********\n%s' % e)
                sys.exit(1)
            else:
                if settings.DEL_FILE_AFTER_LOAD:
                    try:
                        os.remove(load_file)
                    except Exception,e:
                        log.error('remove '+load_file+' error:\n'+e)
                    else:
                        log.info(load_file+' removed ')
                else:
                    log.info('keep file %s\n' % load_file)
        else:
            log.info('skip file %s' % src_file)

        if settings.BAK:
            shutil.move(src_file, settings.BAK_DIR + pure_file_name + settings.FILE_SUFFIX)
            log.info('bak from %s to %s%s%s.' % (src_file, settings.BAK_DIR,pure_file_name,settings.FILE_SUFFIX))
        else:
            log.info('bak is set to False.')
    else:
        print 'skip null src_file\n'
